/**
 * @description:
 * @author: 梅雄
 * @createDate: 2021/12/26
 * @version: 1.0
 * @status: done
 */
package com.xhwl.centiotdata.suppliersystem.yidea;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhwl.centiotdata.pojo.dto.eesd.EesdConfigDTO;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.cent.eesd.EnvDataReqDTO;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 望美制造 - 资产管理
 * mx
 */
@Component
public class AssetsHandlerUtil {

    @Autowired
    RedisUtils redisUtils;

    /**
     * 获取资产
     */
    Object getAssets(EesdConfigDTO.Assets assets, EnvDataReqDTO envDataReqDTO) {
        Map<String, Object> map = Maps.newHashMap();
        int skip = (envDataReqDTO.getPageNum() - 1) * envDataReqDTO.getSize();
        map.put("skip", skip);
        map.put("take", envDataReqDTO.getSize());
        map.put("format", "json");
        map.put("include", "total");
        String token = getToken(assets);
        String host = assets.getApiHost() + "/v1/asset?" + toEqualString(map);
        String result = HttpRequest.get(host).header("Authorization", "Bearer " + token).execute().body();
        Map resMap = JSON.parseObject(result, Map.class);
        Object total = resMap.get("total");
        Object totalAmount = ((Map) resMap.get("meta")).get("totalAmount");
        List<Map<String, Object>> results = (List<Map<String, Object>>) resMap.get("results");
        Map arrayMap = Maps.newLinkedHashMap();
        arrayMap.put("total", total);
        arrayMap.put("pageNum", envDataReqDTO.getPageNum());
        arrayMap.put("size", envDataReqDTO.getSize());
        arrayMap.put("totalAmount", totalAmount);
        arrayMap.put("list", getRes(results));
        return arrayMap;
    }

    /**
     * 获取资产结果
     */
    private List getRes(List<Map<String, Object>> results) {
        if (ChkUtil.isNull(results)) {
            return Lists.newArrayList();
        }
        List<Map<String, Object>> list = Lists.newLinkedList();
        Map<String, Object> lastMap;
        for (Map<String, Object> result : results) {
            lastMap = Maps.newLinkedHashMap();
            lastMap.put("assetCode", ChkUtil.getString(result.get("id"), null));
            lastMap.put("assetName", ChkUtil.getString(result.get("name"), null));
            lastMap.put("assetState", ChkUtil.getString(result.get("state"), null));
            lastMap.put("assetTypeCode", ChkUtil.getString(result.get("assetTypeCode"), null));
            lastMap.put("assetType", ChkUtil.getString(result.get("assetTypeName"), null));
            lastMap.put("assetAddress", ChkUtil.getString(result.get("address"), null));
            lastMap.put("assetManager", ChkUtil.getString(result.get("userEmployeeName"), null));
            lastMap.put("assetPicture", ChkUtil.getString(result.get("picturePath"), null));
            lastMap.put("assetDetail", result.get("tags"));
            list.add(lastMap);
        }
        return list;
    }


    /**
     * 获取维修列表
     */
    Object getRepair(EesdConfigDTO.Assets assets, EnvDataReqDTO envDataReqDTO) {
        Map<String, Object> map = Maps.newHashMap();
        int skip = (envDataReqDTO.getPageNum() - 1) * envDataReqDTO.getSize();
        map.put("skip", skip);
        map.put("take", envDataReqDTO.getSize());
        map.put("format", "json");
        map.put("include", "total");
        String token = getToken(assets);
        String host = assets.getApiHost() + "/v1/receipt/repair?" + toEqualString(map);
        String result = HttpRequest.get(host).header("Authorization", "Bearer " + token).execute().body();
        Map resMap = JSON.parseObject(result, Map.class);
        Object total = resMap.get("total");
        List<Map<String, Object>> results = (List<Map<String, Object>>) resMap.get("results");
        Map arrayMap = Maps.newLinkedHashMap();
        arrayMap.put("total", total);
        arrayMap.put("pageNum", envDataReqDTO.getPageNum());
        arrayMap.put("size", envDataReqDTO.getSize());
        arrayMap.put("list", getRepairRes(results));
        return arrayMap;
    }

    /**
     * 获取维修列表结果
     */
    private List getRepairRes(List<Map<String, Object>> results) {
        if (ChkUtil.isNull(results)) {
            return Lists.newArrayList();
        }
        List<Map<String, Object>> list = Lists.newLinkedList();
        Map<String, Object> lastMap;
        for (Map<String, Object> result : results) {
            lastMap = Maps.newLinkedHashMap();
            lastMap.put("assetRepairer", ChkUtil.getString(result.get("user"), null));
            lastMap.put("repairStatus", ChkUtil.getString(result.get("repairStatus"), null));
            lastMap.put("content", ChkUtil.getString(result.get("content"), null));
            lastMap.put("repairStartTime", result.get("repairDate"));
            lastMap.put("repairEndTime", result.get("completeDate"));
            lastMap.put("repairDetail", result.get("dataJson"));
            List<Map<String, Object>> assets = (List<Map<String, Object>>) result.get("assets");
            for (Map<String, Object> res : assets) {
                lastMap.put("assetCode", ChkUtil.getString(res.get("assetId"), null));
                lastMap.put("assetName", ChkUtil.getString(res.get("name"), null));
                lastMap.put("assetType", ChkUtil.getString(res.get("assetTypeName"), null));
                lastMap.put("assetTypeCode", ChkUtil.getString(res.get("assetTypeCode"), null));
                lastMap.put("assetAddress", ChkUtil.getString(res.get("address"), null));
                lastMap.put("assetManager", ChkUtil.getString(res.get("supervisor"), null));
                lastMap.put("assetPicture", ChkUtil.getString(res.get("picturePath"), null));
                list.add(lastMap);
            }
        }
        return list;
    }

    /**
     * 获取token
     */
    private String getToken(EesdConfigDTO.Assets assets) {
        Object ret = redisUtils.get("wmzz.assets");
        if (ret != null) {
            return (String) ret;
        }
        String host = assets.getAuthHost() + "/connect/token";
        Map<String, Object> map = Maps.newHashMap();
        map.put("grant_type", "password");
        map.put("client_id", assets.getClientId());
        map.put("username", assets.getUsername());
        map.put("password", assets.getPassword());
        map.put("EnterpriseKey", assets.getEnterpriseKey());
        //发起鉴权
        String result = HttpUtil.post(host, map, 3000);
        Map<String, Object> res = JSON.parseObject(result, Map.class);
        String accessToken = (String) res.get("access_token");
        redisUtils.setWithMinute("wmzz.assets", accessToken, (int) res.get("expires_in") / 60 - 1);
        return accessToken;
    }

    /**
     * Map条件转成url
     */
    private static String toEqualString(Map<?, ?> map) {
        List<String> result = new ArrayList<>();
        map.entrySet().parallelStream().reduce(result, (first, second) -> {
            first.add(second.getKey() + "=" + second.getValue());
            return first;
        }, (first, second) -> {
            if (first == second) {
                return first;
            }
            first.addAll(second);
            return first;
        });
        return StringUtils.join(result, '&');
    }
}
